package com.ncr.travel.tas.configuration.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;

import com.ncr.travel.tas.configuration.model.ConfigurationModelObject;

public class GenericDaoJpa<T extends ConfigurationModelObject> implements GenericDao<T> {

	private Class<T> type;

	@PersistenceContext
	protected EntityManager entityManager;

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public GenericDaoJpa(Class<T> type) {
		super();
		this.type = type;
	}

	@Transactional(readOnly = true)
	public T get(Long id) {

		return entityManager.find(type, id);
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<T> getAll() {
		return entityManager.createQuery("select o from " + type.getName() + " o").getResultList();
	}

	@Transactional
	public void save(T object) {
		entityManager.persist(object);
		entityManager.flush();
	}

	@Transactional
	public void delete(Long id) {
		Object found = entityManager.getReference(this.type, id);
		entityManager.remove(found);
	}

	@Transactional
	public void update(T object, long id) {

		entityManager.merge(object);
		entityManager.flush();

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> find(String sql) {

		Query q = entityManager.createQuery(sql);
		return q.getResultList();

	}

}
